<template>
  <z-paging
    ref="paging"
    :refresher-out-rate="0.8"
    :show-empty-view-reload-when-error="false"
    :empty-view-img-style="{ width: '308rpx', height: '308rpx' }"
    empty-view-error-img="https://oneredhealth.oss-cn-hangzhou.aliyuncs.com/2023/10/12/1c53b8aed0c74201bb092265803a1d48.png"
    empty-view-img="https://oneredhealth.oss-cn-hangzhou.aliyuncs.com/2023/10/12/987eadb1d50949a0a7e25dbbd99abe30.png"
    empty-view-error-text="暂无数据"
    bg-color="#F9FAFB"
    v-model="dataList"
    @query="queryList"
    :use-virtual-list="false"
  >
    <view class="bannerBox" slot="top">
      <u-swiper
        :radius="0"
        :list="bannerList"
        indicator
        indicatorMode="line"
        @click="openBanner"
        @change="(e) => (current = e.current)"
        height="280rpx"
        keyName="pictureUrl"
        imgMode="scaleToFill"
        circular
      >
        <view slot="indicator" class="indicator">
          <view
            class="indicator__dot"
            v-for="(item, index) in bannerList"
            :key="index"
            :class="[index === current && 'indicator__dot--active']"
          ></view>
        </view>
      </u-swiper>

      <view class="contentBox">
        <u-grid :border="false" col="4">
          <u-grid-item
            v-for="(listItem, listIndex) in list"
            :key="listIndex"
            @click="toPage(listItem.type, listItem.path)"
          >
            <u-icon
              :customStyle="{ paddingTop: 20 + 'rpx' }"
              :name="listItem.name"
              :size="44"
			  :height="54"
              labelColor="#3D3D3D"
              labelSize="28rpx"
            ></u-icon>
            <text class="grid-text">{{ listItem.title }}</text>
          </u-grid-item>
        </u-grid>
      </view>
    </view>
    <view class="contents">
      <!-- 热门套餐 -->
      <view>
        <view class="flex_wrap row_middle">
          <view class="title"></view>
          <u-text text="热门套餐" bold size="32rpx" color="#3D3D3D" />
        </view>
        <u-gap height="32rpx" />
        <view
          class="packages flex_wrap row_middle"
          v-for="(item, index) in dataList"
          :key="index"
          @click="to_goodsDetail(item.id)"
        >
          <u-image
            :src="item.thumbnail"
            radius="12rpx"
            width="176rpx"
            height="176rpx"
          />
          <view class="lineBox">
            <u-text
              lines="1"
              lineHeight="40rpx"
              :text="item.goodsName"
              size="28rpx"
              color="#3D3D3D"
            />
            <u-gap height="50rpx" />
            <view class="hotGood_price">
              <text>{{ formatDecimal(numDiv(item.price, 100)) }}</text>
            </view>
          </view>
        </view>
      </view>
    </view>
  </z-paging>
</template>

<script>
import { mapGetters } from "vuex";
import caches from "@/config/caches.js";
import {
  getListConfigBanner,
  getGoodsListApiNologin,
  getGoodsListApi,
} from "@/api/shop.js";
import { formatDecimal } from "@/utils/index.js";
import { getCustomerInfoByToken, getByPhone } from "@/api/login.js";
import { numDiv } from "@/js_sdk/nl-precisionNum/precisionNum.js";
export default {
  data() {
    return {
      list: [
        {
          name: "https://oneredhealth.oss-cn-hangzhou.aliyuncs.com/2025/05/27/73c434624ff949a3a4d40b5677bd22f4.png",
          title: "数字人",
          type: "1",
          path: "",
        },
        {
          name: "https://oneredhealth.oss-cn-hangzhou.aliyuncs.com/2025/05/27/f0e03e7836024a3f85a86494e7e538f5.png",
          title: "福鸡",
          type: "2",
          path: "/pages_shop1/pay/chickenDetail/choose",
        },
        {
          name: "https://oneredhealth.oss-cn-hangzhou.aliyuncs.com/2025/05/27/e3397c8f30c945369f821c2142c38b96.png",
          title: "咨询",
          type: "3",
          path: "",
        },
        {
          name: "https://oneredhealth.oss-cn-hangzhou.aliyuncs.com/2025/05/27/41cc88e5b78e443cbbc025aedb075527.png",
          title: "报告",
          type: "4",
          path: "",
        },
        {
          name: "https://oneredhealth.oss-cn-hangzhou.aliyuncs.com/2025/05/27/8c6e25c0d44b41fdb66e51740401a40c.png",
          title: "科普",
          type: "5",
          path: "/pages_video/video/index",
        },
        {
          name: "https://oneredhealth.oss-cn-hangzhou.aliyuncs.com/2025/05/27/c3dbb53a46d9452f94eaca368a1ed5d0.png",
          title: "会员",
          type: "6",
          path: "/pages_else/order/index",
        },
        {
          name: "https://oneredhealth.oss-cn-hangzhou.aliyuncs.com/2025/05/27/bde5115dca11413387ce36ab5522e92a.png",
          title: "体检",
          type: "7",
          path: "",
        },
        {
          name: "https://oneredhealth.oss-cn-hangzhou.aliyuncs.com/2025/05/27/21c6c6ac2f2642bab5165ff5c6be2538.png",
          title: "中医",
          type: "8",
          path: "",
        },
      ],
      bannerList: [], //轮播图
      dataList: [],
      formatDecimal: formatDecimal,
      numDiv,
      current: 0, // 添加 current 属性
    };
  },
  computed: {
    ...mapGetters(["isLogin", "userInfo", "memberFlag"]),
  },
  created() {
    if (this.isLogin) {
      try {
        getCustomerInfoByToken().then((res) => {
          if (res && res.data) {
            this.memberFlag = res.data.memberFlag; //0客户  1会员
            this.$store.commit("SET_MEMBERFLAG", this.memberFlag);
          }
        }).catch((err) => {
          console.error('获取用户信息失败:', err);
        });
      } catch (error) {
        console.error('获取用户信息异常:', error);
      }
    }
  },
  methods: {
    getConfigBanner() {
      try {
        getListConfigBanner("0", this.$wxConfig.tendId).then((res) => {
          const { code, data = [] } = res;
          if (code === 200) this.bannerList = data;
        }).catch((err) => {
          console.error('获取banner失败:', err);
        });
      } catch (error) {
        console.error('获取banner异常:', error);
      }
    },
    // 点击 banner
    openBanner(index) {
      if (!this.isLogin)
        return uni.navigateTo({
          url: "/pages/user/phone/indexApp",
        });
      const {
        bannerType,
        productId = "",
        id = "",
        activePagePath = "",
      } = this.bannerList[index];
      // 0:仅图片 1:商品 2:网址链接 3:图文文章 4:视频 5：活动地址）
      let url;
      if (bannerType === "0") return;
      if (bannerType === "1" && productId)
        url = `pages_shop1/goods/index?id=${productId}`;
      if (["2", "3", "4"].includes(bannerType))
        url = `pages_shop1/banner/index?id=${id}`;
      if (bannerType === "5") url = activePagePath;
      url &&
        uni.$u.route({
          url,
        });
    },
    to_goodsDetail(e) {
      //去详情先判断是否登录
      // if (!this.isLogin)
      // 	return uni.navigateTo({
      // 		url: "/pages/user/phone/indexApp",
      // 	});
      uni.$u.route({
        url: `pages_shop1/goods/index?id=${e}`,
      });
    },
    async toPage(type, path) {
      let token = "";
      try {
        const res = await getByPhone({ source: '十蜂健康小程序跳转注册' });
        if (res && res.code === 200) {
          token = res.data;
        }
      } catch (error) {
        console.error('获取token失败:', error);
      }

      if (type == 1) {
       
        const h5Url = "https://health-h5.oneredhealth.com";
        const queryStr = `token=${encodeURIComponent(token)}`;

        const fullUrl = `${h5Url}?${queryStr}`;
        // 构造目标页面的 URL，包含 H5 页面的完整 URL
        uni.navigateTo({
          url: `/pages/webview/index?url=${encodeURIComponent(fullUrl)}`,
        });
        // uni.navigateToMiniProgram({
        // 	appId: "wx78222dd79fa05607",
        // 	path: `/pages/index/index`, // 不填默认首页
        // 	success(res) {},
        // });
      } else if (type == 3) {
        // 咨询 - 企业微信客服APP端不支持，使用uni.makePhoneCall代替
        uni.showModal({
          title: '提示',
          content: '是否拨打客服电话？',
          success: function(res) {
            if (res.confirm) {
              uni.makePhoneCall({
                phoneNumber: '400-8596-598', // 替换为实际客服电话
                success: function() {
                  console.log('拨打电话成功');
                },
                fail: function() {
                  uni.showToast({
                    title: '拨打失败',
                    icon: 'none'
                  });
                }
              });
            }
          }
        });
      } else if (type == 4) {
        // 报告 - 提示去小程序使用
        uni.showToast({
          title: '请前往小程序使用此功能',
          icon: 'none',
          duration: 2000
        });
      } else if (type == 6) {
        if (this.memberFlag == 1) {
          uni.navigateTo({
            url: `/pages_my1/beSalesman/indexYes`,
          });
        } else {
          uni.navigateTo({
            url: "/pages_my1/beSalesman/index",
          });
        }
      } else if (type == 7) {
        // 体检 - 提示去小程序使用
        uni.showToast({
          title: '请前往小程序使用此功能',
          icon: 'none',
          duration: 2000
        });
      } else if (type == 8) {
        // 中医 - 提示去小程序使用
        uni.showToast({
          title: '请前往小程序使用此功能',
          icon: 'none',
          duration: 2000
        });
      } else {
        uni.$u.route({
          url: path,
        });
      }
    },
    async queryList(pageNo, pageSize) {
      console.log('开始查询商品列表, pageNo:', pageNo, 'pageSize:', pageSize);
      try {
        this.goodsData = {
          pageNum: pageNo,
          pageSize: pageSize,
          tenantId: this.$wxConfig.tendId,
          queryType: 2,
        };
        const result = uni.getStorageSync(caches.ACCESS_TOKEN)
          ? await getGoodsListApi(this.goodsData)
          : await getGoodsListApiNologin(this.goodsData);
        console.log('查询结果:', result);
        
        // 处理返回的数据结构
        const rows = (result && result.data && result.data.rows) || [];
        console.log('提取数据:', '数据数=' + rows.length);
        this.$refs.paging.complete(rows);
        this.getConfigBanner();
      } catch (error) {
        console.error('查询商品列表失败:', error);
        // 错误时也需要调用 complete 让 z-paging 停止 loading
        if (this.$refs && this.$refs.paging) {
          this.$refs.paging.complete([]);
        }
      }
    },
    toLogin() {
      uni.navigateTo({
        url: "/pages/login/index",
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.bannerBox {
  width: 100%;
  // height: 280rpx;
}

.indicator {
  @include flex(row);
  justify-content: center;

  &__dot {
    border-radius: 100px;
    width: 10rpx;
    height: 10rpx;
    background: rgba(255, 255, 255, 0.5);
    margin: 0 10rpx;
    transition: background-color 0.3s;

    &--active {
      width: 30rpx;
      height: 10rpx;
      background: rgba(255, 255, 255, 0.8);
      border-radius: 4000rpx 4000rpx 4000rpx 4000rpx;
      opacity: 1;
    }
  }
}

.contents {
  overflow: auto;
  padding: 20rpx 32rpx;
}

.contentBox {
  padding: 0 10rpx 20rpx;
  background: #ffffff;
  border-radius: 24rpx;
  margin: 20rpx 32rpx 26rpx;
}

.title {
  width: 6rpx;
  height: 28rpx;
  background: #417afd;
  margin-right: 16rpx;
}

.lineBox {
  height: 168rpx;
  margin-left: 24rpx;
}

.packages {
  margin-bottom: 28rpx;
}

.hotGood_price {
  font-size: 32rpx;
  color: #ff0000;
  display: block;
}

.hotGood_price_t {
  font-size: 24rpx;
}
</style>
